/**
 * 用户状态
 */
import buildMenus from '@/utils/menuTree'

/* 引入token操作接口 */
import { getUserId, getToken, setUserId } from '@/utils/auth'

import { sysUser } from '@/api/platformApi'

const user = {
  state: {
    menus: [],
    userId: getUserId(),
    token: getToken(),
    userName: '',
    departMent: '',
    officeId: ''
  },

  mutations: {
    setMenus: (state, menus) => {
      state.menus = [{
        id: 0,
        keyId: 0,
        title: '首页',
        component: '首页',
        path: '/',
        params: {},
        query: {},
        parentId: 0,
        leaf: true,
        hidden: false,
        icon: '',
        children: null
      },
      buildMenus(menus, state.routeMapping)
      ]
      let pashSet = new Set()
      let menuIdSet = new Set()
      let obj = {}
      let arr = []
      menus.forEach(item => {
        pashSet.add(item.path)
        menuIdSet.add(item.menuId)
      })
      arr = Array.from(menuIdSet)
      Array.from(pashSet).forEach((item, index) => {
        obj[item] = arr[index]
      })
      state.menuObject = obj
    },
    // 设置用户id
    setUserId (state, userId) {
      state.userId = userId
    },
    setToken (state, token) {
      state.token = token
    },
    // 设置用户名
    setuserName (state, userName) {
      state.userName = userName
    },
    // 设置部门科室
    setDepartMent (state, departMent) {
      state.departMent = departMent
    },
    // 设置机构Id
    setofficeId (state, officeId) {
      state.officeId = officeId
    }
  },

  actions: {
    // 获取用户信息
    getUserInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        sysUser.getUser().then(res => {
          commit('setuserName', res.name)
          commit('setDepartMent', res.companyName)
          commit('setofficeId', res.officeId)
          setUserId(res.id)
          commit('setUserId', res.id)
          // commit('setuserName', '李柯')
          // commit('setDepartMent', '净化技术研究所')
          resolve(res)
        })
      })
    }
  }
}

export default user
